package com.runchinaup.runchilibrary.modes.adapter;

import android.content.Context;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;

/**
 * Created by liber on 2018/1/24.
 */

public abstract class ListBaseAdapter<D, T extends ListBaseAdapter.Tag> extends BaseAdapter {

    protected Context context;
    protected List<D> datas = null;
    protected DisplayMetrics dm = new DisplayMetrics();

    public ListBaseAdapter(Context context, List<D> datas) {
        this.context = context;
        this.datas = datas;
    }

    @Override
    public int getCount() {
        return datas.size();
    }

    @Override
    public Object getItem(int position) {
        return datas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        final D d = datas.get(position);

        T t;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(loaditemView(), null);
            t = instanceTag(convertView);
        } else {
            t = (T) convertView.getTag();
        }

        handDataAndView(t, d, position);

        return convertView;
    }

    protected abstract int loaditemView();

    protected abstract T instanceTag(View convertView);

    protected abstract void handDataAndView(T t, D d, int position);

    public static class Tag {
        public View view;

        public Tag(View view) {
            this.view = view;
            view.setTag(this);
        }

        protected <V extends View> V $View(int id) {
            return (V) view.findViewById(id);
        }
    }
}
